/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package devbureau.servlet;

import devbureau.fstore.common.DeliveryData;
import devbureau.fstore.common.StoreFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author Expression SSheypak
 */
public class DownloadFileServlet extends HttpServlet{
    private static final Logger log = Logger.getLogger(DownloadFileServlet.class);
    private static final int BUFF_SIZE = 512;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String fileId = request.getParameter(Constants.DELIVERY_ID);
        ByteArrayInputStream in = null;
        ServletOutputStream op = response.getOutputStream();
        try{
            DeliveryData delivery = StoreFactory.getStore().getDelivery(Integer.valueOf(fileId));
            
            ServletContext context  = getServletConfig().getServletContext();
            String mimetype = context.getMimeType( delivery.getFileName() );

            response.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
            response.setContentLength( (int)delivery.getContent().length );
            response.setHeader( "Content-Disposition", "attachment; filename=\"" + delivery.getFileName() + "\"" );

            int length = 0;
            byte[] bbuf = new byte[BUFF_SIZE];
            in = new ByteArrayInputStream(delivery.getContent());

            while ((in != null) && ((length = in.read(bbuf)) != -1))
            {
                op.write(bbuf,0,length);
            }
        }catch(Throwable thr){
            log.error("Error while downloading file", thr);
        }
        finally{
            in.close();
            op.flush();
            op.close();
        }
    }
}
